<template>
  <div>
    <a-card style="margin-bottom: 20px; width: initial; border-radius: 15px">
      <h1>修改闲置</h1>
      <br/>
      <span>🌤不再使用的东西回收利用起来</span>
    </a-card>
    <a-card style="width: auto; height: 650px; border-radius: 15px">
      <a-form-model v-show="!showResult" ref="ruleForm"
                    :rules="rules"
                    :model="form"
                    :label-col="labelCol"
                    :wrapper-col="wrapperCol">
        <a-form-model-item prop="name" label="宝贝名称" :colon="false">
          <a-input v-model="form.name" placeholder="宝贝名称" />
        </a-form-model-item>
        <a-form-model-item prop="price" label="售卖价格" :colon="false">
          <a-input prefix="￥" v-model="form.price" suffix="RMB" placeholder="售卖价格"/>
        </a-form-model-item>
        <a-form-model-item prop="purchaseDate" label="购买日期" :colon="false">
          <a-date-picker v-model="form.purchaseDate" type="date" placeholder="购买日期"/>
        </a-form-model-item>
        <a-form-model-item prop="tagList" label="宝贝标签" :colon="false">
          <a-select v-model="form.tagList" mode="multiple" placeholder="给宝贝归类吧" @change="handleChange">
            <a-select-option v-for="tag in tags" :key="tag.name">
              {{tag.name}}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item prop="description" label="详细描述" :colon="false">
          <a-textarea
              v-model="form.description"
              placeholder="详细的描述更有助于宝贝的出售哦"
              :auto-size="{ minRows: 3, maxRows: 5 }"
          />
        </a-form-model-item>
        <a-form-model-item prop="img" label="宝贝图片" :colon="false">
          <a-upload
              name="avatar"
              list-type="picture-card"
              class="avatar-uploader"
              :show-upload-list="false"
              action="http://localhost:8080/api/file/upload"
              :before-upload="beforeUpload"
              @change="handleImgChange"
              :headers="headers"
          >
            <img v-if="this.form.img" :src="this.form.img" alt="宝贝图片" style="width: 100%"/>
            <div v-else>
              <a-icon :type="uploading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">
                上传
              </div>
            </div>
          </a-upload>
        </a-form-model-item>
        <a-form-model-item >
          <a-button type="primary" @click="submitForm('ruleForm')" style="width: 30%; margin-left: 25%">
            修改
          </a-button>
          <a-button @click="resetForm('ruleForm')" style="margin-left: 20px; width: 30%">
            重置
          </a-button>
        </a-form-model-item>
      </a-form-model>
      <a-result
          v-show="showResult"
          status="success"
          title="修改成功"
          sub-title="可在'个人中心'中查看修改的商品"
      >
        <template #extra>
          <a-button key="console" type="primary" @click="toMyPage">
            返回个人中心
          </a-button>
        </template>
      </a-result>
    </a-card>
  </div>
</template>

<script>
import userStore from "@/store/modules/user";
import {getGoodById, updateGoodById} from "@/services/good";
import {getTagList} from "@/services/tag";
export default {
  name: "EditGood",
  data() {
    // 标签个数校验规则
    let verifyTags = (rule, value, callback) => {
      if (this.form.tagList.length > 5) {
        callback(new Error('标签不能大于5个'));
      } else {
        callback();
      }
    }
    return {
      // 表单相关参数
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      form: {
        name: '',
        price: '',
        purchaseDate: undefined,
        description: '',
        tagList: [],
        img: ''
      },
      rules: {
        name: [
          {required: true, message: '请输入宝贝名称', trigger: 'blur'},
          {min: 1, max: 20, message: '长度需要小于20', trigger: 'blur'},
        ],
        price: [
          {required: true, message: '请输入宝贝价格', trigger: 'blur'},
          {pattern: '^[0-9]+(.[0-9]{2})?$', message: '请输入正确的价格格式', trigger: 'blur'}
        ],
        purchaseDate: [
          {required: true, message: '请选择购买日期', trigger: 'change'},
        ],
        description: [
          {max: 500, message: '描述内容需要小于500', trigger: 'blur'}
        ],
        tagList: [
          {validator: verifyTags, trigger: 'change'}
        ]
      },
      tags: [], // 标签列表（所有）
      showResult: false, // 显示提交结果
      /// 图片上传参数
      uploading: false, // 上传图片加载
      headers: { // 上传图片请求头
        Authorization: "Bearer " + userStore.state.token,
      },
    }
  },
  mounted() {
    this.initGoodInfo() // 初始化修改商品信息
    this.initTagList() // 初始化标签列表
  },
  methods: {
    initGoodInfo() {
      // TODO 发送请求：通过id查询商品
      getGoodById(this.$route.params.id).then(res => {
        if (res.code === 20000) {
          this.form = res.data
          this.form.price = this.form.price.toString() // 前端price是字符串，因为要使用正则表达式校验
        } else {
          console.log(res.message)
        }
      }).catch(() => {
        console.log('通过id查询商品请求错误')
      })
    },
    initTagList() {
      // TODO 发送获取标签列表请求
      getTagList().then(res => {
        if (res.code === 20000) {
          this.tags = res.data
        } else {
          console.log(res.message)
        }
      }).catch(() => {
        console.log('获取标签列表错误')
      })
    },
    // 标签选择器回调函数
    handleChange(value) { // 这个函数其实没啥用，可以测试用，但不能删
      // 注意这里的value是tag.name，不是id，不设为id是因为id不能进行标签搜索
      console.log(`selected ${value}`)
      console.log(this.form.tagList)
    },
    /// 表单操作 ////
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // TODO 更新商品请求
          let goodInfo = {masterId: userStore.state.id, ...this.form}
          updateGoodById(this.$route.params.id, goodInfo).then(res => {
            if (res.code === 20000) {
              // 提交成功，显示结果页面
              this.showResult = true
            } else {
              console.log(res.message)
            }
          }).catch(() => {
            console.log('更新商品请求错误')
          })
        } else {
          return false;
        }
      });
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 上传图片执行操作
    handleImgChange(info) {
      if (info.file.status === 'uploading') {
        this.loading = true; // 上传图片加载
        return;
      }
      if (info.file.status === 'done') {
        this.form.img = info.file.response.data // 设置图片url
        this.loading = false;
      }
      if (info.file.status === 'error') {
        this.loading = false;
        this.$message.error('图片上传失败')
        return;
      }
    },
    // 上传前判断图片是否合规
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.$message.error('只能上传jpeg和png格式图片');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('图片大小需要小于2MB');
      }
      return isJpgOrPng && isLt2M;
    },
    // 返回首页
    toMyPage() {
      this.$router.push('/my/space')
    }
  }
}
</script>

<style scoped>
.numeric-input .ant-tooltip-inner {
  min-width: 32px;
  min-height: 37px;
}

.numeric-input .numeric-input-title {
  font-size: 14px;
}
</style>
